package org.bootstrap.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.bootstrap.service.Impl.TabServiceImpl;
import org.bootstrap.types.Random;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

@CrossOrigin
@RestController
@RequestMapping(value = "tab", method = {RequestMethod.POST, RequestMethod.GET, RequestMethod.OPTIONS})
public class TabController {

    @Resource
    private TabServiceImpl tabService;

    @GetMapping("/list")
    public ArrayList<HashMap<String, Object>> tab_list() {
        return tabService.query_all();
    }

    @PostMapping("/push")
    public JSONObject tab_add(@RequestBody(required = false) HashMap<String, Object> body) {
        Object data = body.getOrDefault("param", null);
        JSONObject res = JSONUtil.createObj();
        if (!Objects.isNull(data)) {
            try {
                JSONObject jsonBody = JSONUtil.parseObj(body).getJSONObject("param");
                String id = RandomUtil.randomString(Random.NumberChar, 8);
                JSONArray tags = jsonBody.getJSONArray("tags");
                jsonBody.putOnce("menu_id", id);
                jsonBody.remove("tags");
                tabService.insert_tab(new HashMap<>(jsonBody));
                ArrayList<HashMap<Object, Object>> outer = new ArrayList<>();
                tags.forEach(item -> {
                    HashMap<Object, Object> innter = new HashMap<>();
                    JSONUtil.parseObj(item).forEach((k, v) -> {
                        if (!k.equalsIgnoreCase("children")) {
                            innter.put(k, v);
                            innter.put("menu_id", id);
                        }
                    });
                    outer.add(innter);
                });
                tabService.insert_tab_child(outer);// 标签
                res.putOnce("result", "success").putOnce("code", 200);
            } catch (Exception e) {
                res.putOnce("result", "error").putOnce("code", 500);
                e.printStackTrace();
            }
            return res;
        }
        return null;
    }

    /**
     * 重命名
     *
     * @param body {map}
     * @return json {code:int,msg:'回执消息‘}
     */
    @PostMapping("/rename")
    public JSONObject tab_rename(@RequestBody(required = false) HashMap<String, Object> body) {
        return tabService.tab_rename(body);
    }

    /**
     * 删除文件夹
     * @
     */
    @PostMapping("/del")
    public JSONObject tab_del(@RequestBody(required = false) HashMap<String, Object> body) {
        return tabService.tab_del(body);
    }
}
